<template>
  <SuperTable ref="superTableRef" search pager border align="center" header-title="备份还原" :columns="columns" :data-request="fetchData" :export-config="{}">
    <template #action>
      <Button type="primary" :loading="state.backupBtnLoading" @click="createBackupFn"> 创建备份 </Button>

      <Button type="primary" :loading="state.uploadBtnLoading">
        <Upload accept=".zip" :show-upload-list="false" :before-upload="beforeUploadFn" :custom-request="customRequestFn">
          <span style="color: #fff">上传恢复</span>
        </Upload>
      </Button>
    </template>
  </SuperTable>
</template>

<script setup lang="ts">
import SuperTable from '@/framework/components/core/super-table/super-table.vue';
import { VxeGridPropTypes } from 'vxe-table';
import type { TableColumnItem } from './columns';
import { baseColumns } from './columns';
import { reactive, ref } from 'vue';
import Button from '@/framework/components/basic/button/button.vue';
import { message, Upload } from 'ant-design-vue';
import { uploadBackup } from '@/api/common/common_data';
import { backupCreate, backupList, backupDelete, restoreById, backupDownload } from '@/api/common/backup';

/**
 * data
 */
const state = reactive({
  uploadBtnLoading: false,
  backupBtnLoading: false,
  restoreState: false,
  downloadState: false,
});

/**
 * backup
 */
const createBackupFn = async () => {
  state.backupBtnLoading = true;
  try {
    await backupCreate();
    message.success('备份成功！');
    refreshTableFn();
  } catch {}
  state.backupBtnLoading = false;
};

/**
 * upload
 */
const beforeUploadFn = () => {
  state.uploadBtnLoading = true;
  return Promise.resolve();
};
const customRequestFn = async (e) => {
  const formData = new FormData();
  formData.append('file', e.file);
  try {
    await uploadBackup(formData);
    message.success('还原成功！');
    e.onSuccess();
  } catch (err) {
    e.onError();
  }
  state.uploadBtnLoading = false;
};

/**
 * table
 */
const superTableRef = ref<InstanceType<typeof SuperTable>>();
const columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    field: '$action',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    width: 200,
    actions: ({ row }) => [
      {
        label: '还原',
        onClick: async () => {
          if (state.restoreState) {
            return message.warn('当前正在还原，请稍后再试！');
          }
          state.restoreState = true;
          try {
            await restoreById(row.id);
            refreshTableFn();
          } catch {}
          state.restoreState = false;
        },
      },
      {
        label: '下载',
        onClick: async () => {
          if (state.downloadState) {
            return message.warn('当前正在下载，请稍后再试！');
          }
          state.downloadState = true;
          try {
            const res = await backupDownload(row.id);
            const fileName = row.path.slice(-18);
            const url = window.URL.createObjectURL(new Blob([res], { type: 'application/zip' }));
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.setAttribute('download', fileName); // 文件名
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a); // 下载完成移除元素
            window.URL.revokeObjectURL(url); // 释放掉blob对象
          } catch {}
          state.downloadState = false;
        },
      },
      {
        label: '删除',
        popConfirm: {
          title: `确认删除该备份吗？`,
          onConfirm: async () => {
            await backupDelete(row.id);
            message.success('操作成功！');
            refreshTableFn();
          },
        },
      },
    ],
  },
];
const fetchData = async (ori: VxeGridPropTypes.ProxyAjaxQueryParams) => {
  let data = superTableRef.value?.getFormModel();
  let params: any = {
    pageSize: ori.page.pageSize,
    pageNum: ori.page.currentPage,
    orderBy: [
      {
        field: 'id',
        order: 'desc',
      },
    ],
  };
  if (data.createTimeBtw) {
    params.createTimeBtw = data.createTimeBtw.join() + ' 23:59:59';
  }
  let res = await backupList(params);
  return res.result;
  // return {
  //   data: [{}, {}, {}],
  //   pageIndex: 1,
  //   pageSize: 10,
  //   total: 100,
  // };
};
const refreshTableFn = () => {
  superTableRef.value?.refreshTable();
};
</script>

<style scoped lang="less"></style>
